package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.utils.ContractNumberGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Objects;

/**
 * 入住Service业务层处理
 * 
 * @author qianyi
 * @date 2025-04-17
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {

        return save(checkIn)?1:0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {

        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo vo = new CheckInDetailVo();
        //查询入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //查询老人详情 老人相关的
        //通过id找到入住配置拿到老 人id
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        if (ObjectUtil.isNotEmpty(elder)){
            CheckInElderVo checkInElderVo = new CheckInElderVo();
            BeanUtils.copyProperties(elder, checkInElderVo);
            //补全年龄属性,通过身份证号来计算老人的年龄,工具类可以使用AI协助创建
            checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
            vo.setCheckInElderVo(checkInElderVo);
        }
        //入住配置
        LambdaQueryWrapper<CheckInConfig> checkInConfigWrapper = new LambdaQueryWrapper<>();
        checkInConfigWrapper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigWrapper);
        //属性拷贝, BeanUtil. toBean:拷贝数据并创建对象(糊涂工具提供)
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        //补全其他属性
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());

        vo.setCheckInConfigVo(checkInConfigVo);

        //查询合同详情
        LambdaQueryWrapper<Contract> contractWrapper = new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId, elder.getId());
        Contract contract = contractMapper.selectOne(contractWrapper);
        vo.setContract(contract);

        //转换家属列表
        String otherApplyInfo = checkIn.getRemark();
        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(otherApplyInfo, ElderFamilyVo.class);
        vo.setElderFamilyVoList(elderFamilyVos);

        return vo;
    }

    /**
     * 入住申请
     *
     * @param dto
     */
    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        try {
            //1.判断老人是否入住，假如老人已经入住，提示：老人已入住，结束程序
            String idCardNo = dto.getCheckInElderDto().getIdCardNo();
            LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
            //根据身份证号查询
            wrapper.eq(Elder::getIdCardNo,idCardNo).eq(Elder::getStatus,1);
            Elder elder = elderMapper.selectOne(wrapper);
            if(ObjectUtil.isNotEmpty(elder)){
                throw new BaseException("老人已入住");
            }
            //2.更新老人选择的床位状态
            Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
            bed.setBedStatus(1);
            bedMapper.updateById(bed);
            //3.更新或新增老人
            elder = insertOrUpdate(bed, dto.getCheckInElderDto());
            //4.新增签约办理信息 合同
            //生成一个合同编号
            String contractNo = "HT" + ContractNumberGenerator.generateContractNumber();
            insertContract(dto, elder,contractNo);
            //5.新增入住信息
            CheckIn checkIn = saveCheckIn(elder, dto, bed);
            //6新增入住配置信息
            insertCheckInConfig(dto, checkIn);
        } catch (BaseException e) {
            throw new BaseException("入住失败");
        }
    }



    //新增入住配置信息
    private void insertCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    //新增入住信息
    private CheckIn saveCheckIn(Elder elder, CheckInApplyDto dto, Bed bed) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(bed.getBedNumber());
        //家属列表，转换为json存在remark字段中
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    //保存合同数据
    private void insertContract(CheckInApplyDto dto, Elder elder, String contractNo) {
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto,contract);
        //缺少老人相关的，合同编号，状态，时间
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        contract.setContractNumber(contractNo);
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        //设置状态
        Integer status = startDate.isAfter(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);

        contractMapper.insert(contract);
    }

    //更新或新增老人
    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        //属性拷贝
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);

        String idCardNo = checkInElderDto.getIdCardNo();
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        //根据身份证号查询
        wrapper.eq(Elder::getIdCardNo,idCardNo).eq(Elder::getStatus,0);
        Elder elderDb = elderMapper.selectOne(wrapper);

        if(ObjectUtil.isNotEmpty(elderDb)){
            elder.setId(elderDb.getId());
            //更新
            elderMapper.updateById(elder);
        }else{
            //新增
            elderMapper.insert(elder);
        }

        return elder;
    }
}
